<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>编辑视频</span>
      </div>

      <el-form ref="videoForm" :model="videoForm" :rules="rules" label-width="120px">
        <el-form-item label="视频标题" prop="video_title">
          <el-input v-model="videoForm.video_title" placeholder="请输入视频标题" />
        </el-form-item>

        <el-form-item label="视频描述" prop="video_desc">
          <el-input v-model="videoForm.video_desc" type="textarea" :rows="4" placeholder="请输入视频描述" />
        </el-form-item>

        <el-form-item label="微信视频链接" prop="video_wxurl">
          <el-input v-model="videoForm.video_wxurl" placeholder="请输入微信视频链接" />
        </el-form-item>

        <el-form-item label="抖音视频链接" prop="video_dyurl">
          <el-input v-model="videoForm.video_dyurl" placeholder="请输入抖音视频链接" />
        </el-form-item>

        <el-form-item label="快手视频链接" prop="video_ksurl">
          <el-input v-model="videoForm.video_ksurl" placeholder="请输入快手视频链接" />
        </el-form-item>

        <el-form-item label="美食店铺" prop="video_shop">
          <el-input v-model="videoForm.video_shop" placeholder="请输入美食店铺名称" />
        </el-form-item>

        <!-- 美食地点 -->
        <el-form-item label="美食地点" prop="location">
          <div class="location-container">
            <div class="location-selects">
              <el-select
                v-model="videoForm.province"
                placeholder="请选择省份"
                class="location-select"
                filterable
                clearable
                @change="handleProvinceChange"
              >
                <el-option v-for="(name, code) in provinceData" :key="code" :label="name" :value="code" />
              </el-select>

              <el-select
                v-model="videoForm.city"
                placeholder="请选择城市"
                :disabled="!videoForm.province"
                class="location-select"
                filterable
                clearable
                @change="handleCityChange"
              >
                <el-option v-for="(name, code) in cityData" :key="code" :label="name" :value="code" />
              </el-select>

              <el-select
                v-model="videoForm.district"
                placeholder="请选择区县"
                :disabled="!videoForm.city"
                class="location-select"
                filterable
              >
                <el-option v-for="(name, code) in districtData" :key="code" :label="name" :value="code" />
              </el-select>
            </div>
            <div class="location-actions">
              <el-input v-model="videoForm.detailAddress" placeholder="请输入详细地址" class="detail-address" />
            </div>
          </div>
        </el-form-item>

        <el-form-item label="来源纪录片" prop="video_produccer">
          <el-input v-model="videoForm.video_produccer" placeholder="请输入来源纪录片" />
        </el-form-item>

        <!-- 视频封面 -->
        <el-form-item label="视频封面" prop="video_coverimg">
          <el-upload
            class="cover-uploader"
            :action="`${domain}/upload/img`"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            :before-upload="beforeCoverUpload"
            :headers="headers"
          >
            <img v-if="videoForm.video_coverimg" :src="videoForm.video_coverimg" class="cover-image">
            <i v-else class="el-icon-plus cover-uploader-icon" />
          </el-upload>
          <div class="cover-tip">建议尺寸：800x450px，支持 jpg、png 格式</div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">保存修改</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>

  </div>
</template>

<script>
import { getVideo, updateVideo } from '@/api/videoapi'
import { pca, pcaa } from 'area-data'

export default {
  name: 'EditVideo',
  data() {
    return {
      domain: process.env.VUE_APP_DOMAIN || 'http://localhost:6688',
      videoForm: {
        video_id: undefined,
        video_title: '',
        video_desc: '',
        video_wxurl: '',
        video_dyurl: '',
        video_ksurl: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        video_produccer: '',
        video_address: '',
        video_shop: '',
        video_coverimg: ''
      },
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      },
      rules: {
        video_title: [
          { required: true, message: '请输入视频标题', trigger: 'blur' },
          { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
        ],
        video_desc: [
          { required: true, message: '请输入视频描述', trigger: 'blur' }
        ],
        video_wxurl: [
          { required: true, message: '请输入微信视频链接', trigger: 'blur' }
        ],
        detailAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        video_produccer: [
          { required: true, message: '请输入制作人', trigger: 'blur' }
        ],
        video_address: [
          { required: true, message: '请输入拍摄地址', trigger: 'blur' }
        ],
        video_shop: [
          { required: true, message: '请输入美食店铺名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        video_coverimg: [
          { required: true, message: '请上传视频封面', trigger: 'change' }
        ]
      },
      provinceData: pca['86'],
      cityData: {},
      districtData: {},
      isEditingLocation: false,
      tempLocationData: null,
      originalProvince: '',
      originalCity: '',
      originalDistrict: '',
      originalProvinceName: '',
      originalCityName: '',
      originalDistrictName: ''
    }
  },
  computed: {
    formatLocation() {
      const parts = []
      if (this.videoForm.province && this.provinceData[this.videoForm.province]) {
        parts.push(this.provinceData[this.videoForm.province])
      }
      if (this.videoForm.city && this.cityData[this.videoForm.city]) {
        parts.push(this.cityData[this.videoForm.city])
      }
      if (this.videoForm.district && this.districtData[this.videoForm.district]) {
        parts.push(this.districtData[this.videoForm.district])
      }
      if (this.videoForm.detailAddress) {
        parts.push(this.videoForm.detailAddress)
      }
      return parts.length > 0 ? parts.join(' ') : '点击设置美食地点'
    }
  },
  created() {
    this.getVideoDetail()
  },
  methods: {
    handleProvinceChange(provinceCode) {
      this.videoForm.city = ''
      this.videoForm.district = ''
      this.cityData = pca[provinceCode] || {}
      this.districtData = {}
    },
    handleCityChange(cityCode) {
      this.videoForm.district = ''
      this.districtData = pcaa[cityCode] || {}
    },
    async getVideoDetail() {
      try {
        const { data } = await getVideo(this.$route.params.id)
        // 处理返回的数据
        this.videoForm = {
          ...data,
          province: data.province_code || data.province,
          city: data.city_code || data.city,
          district: data.district_code || data.district
        }
        // 保存原始省市区代码和名称
        this.originalProvince = this.videoForm.province
        this.originalCity = this.videoForm.city
        this.originalDistrict = this.videoForm.district
        this.originalProvinceName = data.province
        this.originalCityName = data.city
        this.originalDistrictName = data.district

        // 初始化地区数据
        if (this.videoForm.province) {
          this.cityData = pca[this.videoForm.province] || {}
        }
        if (this.videoForm.city) {
          this.districtData = pcaa[this.videoForm.city] || {}
        }
      } catch (error) {
        this.$message.error('获取视频信息失败')
      }
    },
    confirmAddress() {
      if (this.selectedAddress) {
        this.videoForm.video_address = this.selectedAddress.name
        this.addressDialogVisible = false
      } else {
        this.$message.warning('请先选择地址')
      }
    },

    async submitForm() {
      try {
        await this.$refs.videoForm.validate()

        // 准备提交数据
        const submitData = {
          ...this.videoForm
        }

        // 检查省市区是否更改过
        if (this.videoForm.province !== this.originalProvince ||
            this.videoForm.city !== this.originalCity ||
            this.videoForm.district !== this.originalDistrict) {
          // 如果更改过，转换省市区代码为名称
          submitData.province = this.provinceData[this.videoForm.province] || ''
          submitData.city = this.cityData[this.videoForm.city] || ''
          submitData.district = this.districtData[this.videoForm.district] || ''
        } else {
          // 如果没有更改，保持原数据
          submitData.province = this.originalProvinceName
          submitData.city = this.originalCityName
          submitData.district = this.originalDistrictName
        }

        await updateVideo(submitData)
        this.$message.success('更新成功')
        this.goBack()
      } catch (error) {
        this.$message.error('更新失败：' + error.message)
      }
    },
    goBack() {
      this.$router.push('/videos/list')
    },
    // 处理封面上传成功
    handleCoverSuccess(res, file) {
      if (res.code === 20000) {
        this.videoForm.video_coverimg = res.data.url
        this.$message.success('封面上传成功')
      } else {
        this.$message.error(res.message || '封面上传失败')
      }
    },
    // 上传前验证
    beforeCoverUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('封面图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('封面图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    }

  }
}
</script>

<style scoped>
.box-card {
  margin: 20px;
}

.el-cascader {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.map-container {
  display: flex;
  height: 500px;
}

.amap-box {
  flex: 1;
  height: 100%;
}

.search-box {
  width: 300px;
  margin-left: 20px;
}

.search-result {
  margin-top: 10px;
  max-height: 400px;
  overflow-y: auto;
}

.result-item {
  padding: 10px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
}

.result-item:hover {
  background-color: #f5f7fa;
}

.result-item .address {
  font-size: 12px;
  color: #999;
  display: block;
  margin-top: 5px;
}

.location-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  cursor: pointer;
}

.location-display:hover {
  border-color: #409EFF;
}

.location-display .edit-btn {
  padding: 0;
  margin-left: 10px;
}

.location-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.location-selects {
  display: flex;
  gap: 10px;
}

.location-select {
  width: 160px;
}

.location-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.detail-address {
  flex: 1;
}

.cover-uploader {
  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409EFF;
    }
  }
}

.cover-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.cover-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.cover-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>
